package com.thkj.util;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

/**
 * HttpClients 请求工具类
 *
 * @author Leon
 * @datetime 2018年8月13日 下午4:42:17
 */
public class HttpClientUtil {

    private static Logger logger = Logger.getLogger(HttpClientUtil.class);

    private static final CloseableHttpClient httpClient;

    static {
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES)
                .setConnectTimeout(10000).setSocketTimeout(10000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(globalConfig).build();
    }

    public static JSONObject doPost(String url, JSONObject json, String authorization) {
        // CloseableHttpClient client =
        // HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
        HttpPost httpPost = new HttpPost(url);
        JSONObject response = null;
        CloseableHttpResponse res = null;
        try {
            // 设置请求的header
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Accept", "application/json;charset=utf-8");
            httpPost.setHeader("Authorization", authorization);
            StringEntity s = new StringEntity(formatPostData(json), "UTF-8");
            s.setContentEncoding("UTF-8");
            //	s.setContentType("x-www-form-urlencoded");// 发送json数据需要设置contentType
            //	httpPost.setEntity(s);

            res = httpClient.execute(httpPost);
            int statusCode = res.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                logger.info("请求接口返回状态吗, getStatusCode=" + statusCode + ", getReasonPhrase="
                        + res.getStatusLine().getReasonPhrase());
                httpPost.abort();
                throw new Exception("HttpClient,error status code :" + statusCode);
            }

            HttpEntity entity = res.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, "UTF-8");
                response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            logger.error("HTTP-POST请求出错, URL=" + url + "请求数据：" + json, e);
        } finally {
            httpPost.releaseConnection();
            if (res != null) {
                try {
                    EntityUtils.consume(res.getEntity());
                } catch (IOException e) {
                }
                try {
                    res.close();
                } catch (IOException e) {
                }
            }
        }
        return response;
    }


    public static String doPostJson(String url, String json, String authorization) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String rst = null;

        // 请求地址
        HttpPost httpPost = new HttpPost(url);

        //post请求
        try {
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Authorization", authorization);
            httpPost.setEntity(new StringEntity(json, Charset.forName("UTF-8")));
            response = httpclient.execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    rst = EntityUtils.toString(entity, "UTF-8");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rst;
    }

    public static String doPost(String url, Map<String, String> params, String charset) {

        if (StringUtils.isBlank(url)) {
            return null;
        }
        if (StringUtils.isBlank(charset)) {
            charset = "utf-8";
        }
        HttpPost httpPost = null;
        try {
            List<NameValuePair> pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), value));
                    }
                }
            }
            httpPost = new HttpPost(url);
            if (pairs != null && pairs.size() > 0) {
                httpPost.setEntity(new UrlEncodedFormEntity(pairs, charset));
            }
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, charset);
            }
            EntityUtils.consume(entity);
            response.close();
            System.out.println("------------" + result);
            return result;
        } catch (Exception e) {
            if (httpPost != null) {
                httpPost.abort();

            }
            e.printStackTrace();
        }
        return null;
    }

    /**
     * GET请求
     *
     * @param url
     * @return
     */
    public static JSONObject doGet(String url) {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse res = null;
        JSONObject response = null;
        try {
            // 设置请求的header
            httpGet.setHeader("Content-Type", "application/json;charset=utf-8");
            httpGet.setHeader("Accept", "application/json;charset=utf-8");

            res = httpClient.execute(httpGet);
            int statusCode = res.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                logger.info("请求接口返回状态码, getStatusCode=" + statusCode + ", getReasonPhrase="
                        + res.getStatusLine().getReasonPhrase());
                httpGet.abort();
                throw new Exception("HttpClient,error status code :" + statusCode);
            }

            HttpEntity entity = res.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, "UTF-8");
                response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            logger.error("HTTP-GET请求出错, URL=" + url, e);
        } finally {
            httpGet.releaseConnection();
            if (res != null) {
                try {
                    EntityUtils.consume(res.getEntity());
                } catch (IOException e) {
                }
                try {
                    res.close();
                } catch (IOException e) {
                }
            }
        }
        return response;
    }

    protected static String formatPostData(JSONObject json) {
        String result = null;
        try {
            JSONObject jsonObject = json;
            if (jsonObject != null) {
                result = "?";
                for (Entry<String, Object> entry : jsonObject.entrySet()) {
                    if (StringUtils.isEmpty(result)) {
                        result = entry.getKey() + "=" + entry.getValue();
                    } else {
                        result += "&" + entry.getKey() + "=" + entry.getValue();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    protected static String formatPostData(String strdata) {
        String result = strdata;
        try {
            JSONObject jsonObject = JSONObject.parseObject(strdata);
            if (jsonObject != null) {
                result = "";
                for (Entry<String, Object> entry : jsonObject.entrySet()) {
                    if (StringUtils.isEmpty(result)) {
                        result = entry.getKey() + "=" + entry.getValue();
                    } else {
                        result += "&" + entry.getKey() + "=" + entry.getValue();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
